<template>
<div class="roles">
  <!-- 面包屑导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 100%">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>权限列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片区域 -->
  <el-card>
    <!-- 添加角色行 -->
    <el-row>
      <el-col>
        <!-- 添加角色按钮 -->
        <el-button type="primary" @click="addRoleInfo.isShowDialog = true">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- 角色展示表格 -->
    <el-table border stripe :data="rolusList">
      <!-- 折叠行 -->
      <el-table-column type="expand">
        <!-- 作用域插槽,渲染折叠部分的内容 -->
        <template slot-scope="scope">
          <!-- 利用栅格确定渲染位置,循环该行一级权限 -->
          <el-row :class="['bb',i1 === 0 ? 'bt' : '', 'concenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
            <!-- 显示一级权限名称 -->
            <el-col :span="5">
              <el-tag>{{item1.authName}}</el-tag>
              <!-- 向右的图标 -->
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二级权限和三级权限的位置 -->
            <el-col :span="19">
              <!-- 循环二级权限 -->
              <el-row :class="[i2 !== 0 ? 'bt' : '', 'concenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                <!-- 二级权限展示位置 -->
                <el-col :span="6">
                  <!-- 显示二级权限 -->
                  <el-tag type="success">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级权限位置 -->
                <el-col :span="18">
                  <!-- 循环三级权限 -->
                  <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 自增编号 -->
      <el-table-column type="index" label="#"></el-table-column>
      <!-- 角色名称 -->
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <!-- 角色描述 -->
      <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" width="284px">
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRole(scope.row)">编辑</el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delectUser(scope.row.id)">删除</el-button>
          <!-- 修改角色按钮 -->
          <el-button type="warning" icon="el-icon-setting" size="mini" @click="editRight(scope.row)">修改权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 编辑用户权限 -->
  <el-dialog title="编辑用户权限" :visible.sync="isShowEditRight" width="50%" @close="closeEditDialog">

    <!-- 权限树 -->
    <el-tree :data="editUserRight.rights" show-checkbox :props="editUserRight.defaultProps" node-key="id" default-expand-all ref="editUserRightRef" :default-checked-keys="editUserRight.userRolus">
    </el-tree>

    <!-- 弹出框的底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShowEditRight = false">取 消</el-button>
      <el-button type="primary" @click="updataRight">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 添加角色 -->
  <el-dialog title="添加角色" :visible.sync="addRoleInfo.isShowDialog" width="50%" @close="clearAddRoleFrom">

    <!-- 添加角色表单 -->
    <el-form :model="addRoleInfo" :rules="addRoleInfo.rules" ref="addRoleInfoRef" label-width="80px">
      <el-form-item label="角色编号" prop="roleId">
        <el-input v-model="addRoleInfo.roleId"></el-input>
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addRoleInfo.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addRoleInfo.roleDesc"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="addRoleInfo.isShowDialog = false">取 消</el-button>
      <el-button type="primary" @click="addRole">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 编辑角色 -->
  <el-dialog title="编辑角色" :visible.sync="editRoleInfo.isShowDialog" width="50%" @close="clearEditRoleFrom">

    <!-- 编辑角色表单 -->
    <el-form :model="editRoleInfo" :rules="editRoleInfo.rules" label-width="80px">
      <el-form-item label="角色编号" prop="roleId">
        <el-input v-model="editRoleInfo.roleId"></el-input>
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="editRoleInfo.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="editRoleInfo.roleDesc"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="editRoleInfo.isShowDialog = false">取 消</el-button>
      <el-button type="primary" @click="updateRole">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    return {
      // 已授权限列表
      rolusList: [],
      // 控制是否编辑用户权限
      isShowEditRight: false,
      // 修改用户权限相关的数据
      editUserRight: {
        // 要修改的角色id
        uid: null,
        // 所有权限目录
        rights: [],
        // 要修改的用户权限
        userRolus: [],
        // 默认 传值
        defaultProps: {
          children: 'children',
          label: 'authName'
        }
      },
      // 添加用户相关的数据
      addRoleInfo: {
        // 控制弹窗
        isShowDialog: false,
        // 校验规则
        rules: {
          roleId: [
            {
              required: true,
              message: '请输入id',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 3,
              message: '长度为 2 - 3 个数字',
              trigger: 'blur'
            }
          ],
          roleName: [
            {
              required: true,
              message: '请输入角色名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 5,
              message: '长度在 3 到 5 个字符',
              trigger: 'blur'
            }
          ],
          roleDesc: [{
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          }]
        }
      },
      // 编辑角色相关的数据
      editRoleInfo: {
        // 控制弹窗
        isShowDialog: false,
        // 这里没有数据不能填写表单
        roleId: '',
        roleName: '',
        roleDesc: '',
        // 校验规则
        rules: {
          roleId: [
            {
              required: true,
              message: '请输入id',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 3,
              message: '长度为 2 - 3 个数字',
              trigger: 'blur'
            }
          ],
          roleName: [
            {
              required: true,
              message: '请输入角色名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 5,
              message: '长度在 3 到 5 个字符',
              trigger: 'blur'
            }
          ],
          roleDesc: [{
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          }]
        }
      }
    }
  },
  methods: {
    // 获取角色列表
    async getRolusList() {
      // 发送请求，并接收请求数据
      const {
        data: {
          data,
          meta
        }
      } = await this.$http.get('roles')
      // 判单服务器响应结果
      if (meta.status === 200) {
        this.rolusList = data
      } else {
        this.$message.error('角色列表获取失败！')
      }
    },
    // 用 id 单一删除权限
    async removeRightById(role, rightId) {
      // 加载弹出框，确认是否删除
      const rel = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)

      // 判断用户是否取消删除
      if (rel !== 'confirm') return this.$message.info('删除权限已取消')

      // 执行删除操作
      const {
        data: {
          data,
          meta
        }
      } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (meta.status === 200) {
        this.$message.success('删除权限成功')
        // this.getRolusList() 会闭合
        role.children = data
      } else {
        this.$message.error('角色信息获取失败')
      }
    },
    // 打开编辑权限弹出框
    async editRight(role) {
      // 将要修改的角色的 id 保存
      this.editUserRight.uid = role.id
      // 发送请求并接收所有权限的数据
      const {
        data: rightsTree
      } = await this.$http.get('rights/tree')
      // 判断响应数据是否符合要求
      if (rightsTree.meta.status !== 200) return this.$message.error('权限信息获取失败')
      // 这里获取 所有三级权限的 id
      this.findId(role)
      // this.editUserRight.userRolus = [105, 116]
      this.editUserRight.rights = rightsTree.data
      this.isShowEditRight = true
    },
    // 遍历所有的三级权限 id
    findId(obj) {
      if (obj.children) {
        for (const key in obj.children) {
          this.findId(obj.children[key])
        }
      } else {
        this.editUserRight.userRolus.push(obj.id)
      }
    },
    // 关闭编辑后清空 editUserRight.userRolus 中的数据
    closeEditDialog() {
      this.editUserRight.userRolus = []
    },

    // 更新权限
    async updataRight() {
      // 定义请求体
      const rids = this.$refs.editUserRightRef.getCheckedKeys().join()
      // 发送请求
      const {
        data: {
          meta
        }
      } = await this.$http.post('roles/' + this.editUserRight.uid + '/rights', {
        rids
      })
      console.log(this.editUserRight.uid)
      console.log(this.$refs.editUserRightRef.getCheckedKeys())
      // 提示并隐藏
      if (meta.status === 200) {
        this.$message.success('权限更改成功！')
        this.editUserRight.uid = null
        this.isShowEditRight = false
        this.getRolusList()
      } else {
        this.$message.error('权限更改失败！')
      }
    },
    // 添加角色
    async addRole() {
      await this.$refs.addRoleInfoRef.validate(async (valid) => {
        if (valid) {
          // 发送添加角色的请求
          const {
            data
          } = await this.$http.post('roles', {
            roleId: this.addRoleInfo.roleId,
            roleName: this.addRoleInfo.roleName,
            roleDesc: this.addRoleInfo.roleDesc
          })
          console.log(data)
          // 判断服务器返回的状态
          if (data.mate.status !== 201) return this.$message.error('角色添加失败！')

          this.$message.success('角色添加成功！')
          this.addRoleInfo.isShowDialog = false
        } else {
          this.$message.info('验证失败')
          return false
        }
      })
    },
    // 清空添加角色的表单数据
    clearAddRoleFrom() {
      this.addRoleInfo.roleId = ''
      this.addRoleInfo.roleName = ''
      this.addRoleInfo.roleDesc = ''
    },

    // 显示编辑角色对话框，并传递数据
    showEditRole(role) {
      // 初始化编辑面板
      this.editRoleInfo.roleId = role.id
      this.editRoleInfo.roleName = role.roleName
      this.editRoleInfo.roleDesc = role.roleDesc

      this.editRoleInfo.isShowDialog = true
    },
    // 更新角色
    async updateRole() {
      // 向服务器发送更新请求
      const { data } = await this.$http.put('roles/' + this.editRoleInfo.roleId, { roleName: this.editRoleInfo.roleName, roleDesc: this.editRoleInfo.roleDesc })
      // 判断并提示用户结果
      if(data.meta.status === 200) {
        this.$message.success('用户信息更新成功！')
        // 更新页面数据
        this.getRolusList()
        // 隐藏表单
        this.editRoleInfo.isShowDialog = false
      } else {
        this.$message.error('用户信息更新失败！')
      }
    },
    // 关闭清空角色表单数据
    clearEditRoleFrom() {
      this.editRoleInfo.roleId = ''
      this.editRoleInfo.roleName = ''
      this.editRoleInfo.roleDesc = ''
    }
  },
  created() {
    // 初始化数据
    this.getRolusList()
  }
}
</script>

<style lang="less" scoped>
// tab 标签外边距
.el-tag {
  margin: 7px;
}

// 上边框
.bt {
  border-top: 1px solid #eeeeee;
}

// 下边框
.bb {
  border-bottom: 1px solid #eeeeee;
}

// 上下居中对齐
.concenter {
  display: flex;
  align-items: center;
}
</style>
